﻿using GDI_应用案例.Pages;
using GDI_应用案例.Pages.Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GDI_应用案例
{
    public partial class FrmMain : Form
    {
        private readonly SortedDictionary<int, FormPageAttribute> _cache = new SortedDictionary<int, FormPageAttribute>();
        public FrmMain()
        {
            InitializeComponent();
        }

        private void InitFormType(SortedDictionary<int, FormPageAttribute> cache)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            Type pageType = typeof(PageBase);
            Type attributeType = typeof(FormPageAttribute);
            Type[] types = assembly.GetTypes().Where(t => t.IsSubclassOf(pageType) && Attribute.IsDefined(t, attributeType)).ToArray();
            foreach (Type type in types)
            {
                var attr = type.GetCustomAttribute(attributeType) as FormPageAttribute;
                attr.Type = type;
                if (cache.ContainsKey(attr.Key))
                    throw new ArgumentException("Page页存在重复key");
                else
                    cache.Add(attr.Key, attr);
            }
        }

        private async void FrmMain_Load(object sender, EventArgs e)
        {
            await Task.Run(() =>
            {
                InitFormType(_cache);
            });

            foreach (var item in _cache)
            {
                TreeNode treeNode = new TreeNode(item.Value.Text);
                treeNode.Tag = item.Value;
                treeNode.ImageIndex = 0;
                this.treeView1.Nodes.Add(treeNode);
            }

            
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            string text = e.Node.Text;
            FormPageAttribute formPageAttribute = e.Node.Tag as FormPageAttribute;
            if (formPageAttribute == null)
            {
                MessageBox.Show("暂无Page页");
                return;
            }

            if (formPageAttribute.Page == null)
            {
                formPageAttribute.Page = (Form)Activator.CreateInstance(formPageAttribute.Type);
                formPageAttribute.Page.TopLevel = false;
                formPageAttribute.Page.Dock = DockStyle.Fill;
                formPageAttribute.Page.Show();
            }

            panel3.Controls.Clear();
            panel3.Controls.Add(formPageAttribute.Page);
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            foreach (var item in _cache)
            {
                item.Value.Page?.Dispose();
            }
        }
    }
}
